import { createOfflinePlan, eidtOfflinePlan, getOfflinePlanDetail, updateOfflinePlanStatus } from '@/api/OfflineStudy';
import { pageOpeTypeEnum } from '@/common';
import ViewLoading from '@/components/ViewLoading';
import YmCollaPanes from '@/components/YmCollaPanes';
import { useAppSelector } from '@/redux/store';
import { App, Form, Input, InputNumber, Radio, Select, Space, TreeSelect } from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useEntListSelectTreeProps } from './common';
import SelDayTimes from './components/SelDayTimes';
import SelectWeekDays from './components/selectWeekDays';
import SelNoStudyDays from './components/SelNoStudyDays';
import TablePosition from './components/TablePosition';
import OStyle from './index.less';
import { StudyPlanChildProps, StudyPlanChildRef } from './interface';
const requireRules = (text: string) => {
  return [{ required: true, message: text }];
};
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 15 },
};
const OfflineStudyPlan = forwardRef<StudyPlanChildRef, StudyPlanChildProps>((props, ref) => {
  const {
    message,
    modal: { confirm },
  } = App.useApp();
  const navigator = useNavigate();

  const [form] = Form.useForm();
  const { loginRole } = useAppSelector((state) => state.loginUser);
  const { entId, organizationType } = useAppSelector((state) => state.loginEnt); //organizationType 1:协会，0：企业
  const [intervalType, setIntervalType] = useState<string>('1');
  const [collPanesActiveKeys, setCollPanesActiveKeys] = useState([5, 6, 7]);
  // let [rowkey, setrowkey] = useState<number>(0);
  const { onStudyPlanMethodChange, onSubSuccess, type, planCourseId } = props;
  let learnMethod = props.learnMethod;
  const [loading, setLoading] = useState(false);
  //学习对象企业配置
  const EntSelectTree = useEntListSelectTreeProps({
    onSuccess(data) {
      const entList = form.getFieldsValue().entList;
      if (!entList) {
        // 没有就是需要默认给全部
        form.setFieldsValue({
          entList: data.map(({ title, id }) => ({
            entId: id,
            entName: title,
          })),
        });
      }
    },
  });

  const { Option } = Select;
  const selectAfter = (
    <Select
      value={intervalType}
      onChange={(e) => {
        setIntervalType(e);
      }}
    >
      <Option value="1">分钟</Option>
      <Option value="2">小时</Option>
    </Select>
  );
  const _sub = (issue: number) => {
    form.validateFields().then((values) => {
      const params: any = Object.assign({}, values);
      params.entId = entId;
      if (params.signRule == 2 || params.signRule == 3) {
        const keylist = ['addressName', 'latitude', 'longitude', 'scope'];
        let hasvoid = false;
        hasvoid = keylist.some((el) => {
          return !values.positionInfoDto[el];
        });
        if (hasvoid) return message.error('请编辑签到/签退位置');
        params.signAddress = values.positionInfoDto.addressName;
        params.latitude = values.positionInfoDto.latitude;
        params.longitude = values.positionInfoDto.longitude;
        params.scope = values.positionInfoDto.scope;
      }
      if (params.signRule != 3) params.intervalTime = ''; // 如果非签到、签退，间隔传空
      if (params.signRule == 1) params.isFace = 0; // 如果无需签到，人脸传0
      params.intervalType = intervalType;
      params.trainTimeDtoList = values.trainTimeDtoList.map((el: any) => {
        return {
          week: el.value,
          startTrainTime: el.startTrainTime + ':01', // 00秒的话，后端那边逻辑会有问题，详询szn
          endTrainTime: el.endTrainTime + ':01',
        };
      });
      try {
        params.noTrainTimeDtoList = [...values.noTrainTimeDtoList];
      } catch (error) {
        params.noTrainTimeDtoList = [];
      }
      try {
        params.specialTrainTimeDtoList = values.specialTrainTimeDtoList.map((el: any) => {
          return {
            startSpecialTrainTime: el.trainTime + ' ' + el.startTime + ':01',
            endSpecialTrainTime: el.trainTime + ' ' + el.endTime + ':01',
          };
        });
      } catch (error) {
        params.specialTrainTimeDtoList = [];
      }

      console.log(params, '打印看看现在表单数据');
      if (type === pageOpeTypeEnum['edit'] && planCourseId) {
        params.planCourseId = planCourseId;
      }
      let request: any;
      if (type === pageOpeTypeEnum['edit'] && planCourseId) {
        request = eidtOfflinePlan(params);
      } else {
        request = createOfflinePlan(params);
      }

      setLoading(true);
      request
        .then((res: any) => {
          const { code, data, msg } = res;
          if (code === '200') {
            if (data === 1) {
              confirm({
                title: '发布失败',
                content: msg,
                centered: true,
                okText: '前往',
                onOk: () => {
                  if (loginRole == '1' || loginRole == '0') {
                    navigator('/safeService/buyService');
                  } else {
                    message.warning('您暂无权限，请联系企业管理人员！');
                  }
                },
              });
            } else if (data.promptMessage) {
              confirm({
                title: '发布成功',
                content: data.promptMessage,
                centered: true,
                okText: '前往',
                onOk: () => {
                  if (loginRole == '1' || loginRole == '0') {
                    navigator('/safeService/bitAllocation');
                  } else {
                    message.warning('您暂无权限，请联系企业管理人员！');
                  }
                },
              });
            } else {
              if (issue == 1) {
                const params2 = {
                  planCourseId: data,
                  openStatus: 1,
                };
                updateOfflinePlanStatus(params2).then((res: any) => {
                  const { code, data, msg } = res;
                  if (code === '200') {
                    message.success((type === pageOpeTypeEnum['add'] ? '添加' : '编辑') + '成功');
                    onSubSuccess?.();
                  }
                });
              } else {
                message.success((type === pageOpeTypeEnum['add'] ? '添加' : '编辑') + '成功');
                onSubSuccess?.();
              }
            }
          }
        })
        .finally(() => {
          setLoading(false);
        })
        .catch((err: any) => {
          console.log('--AddCircleStudyPlan--createFixedStudyPlan--err--:', err);
        });
    });
  };
  //发布
  const onSubPublish = () => {
    _sub(1);
  };

  //保存
  const onSubSave = () => {
    _sub(0);
  };
  useImperativeHandle(ref, () => ({
    onSubPublish,
    onSubSave,
  }));
  useEffect(() => {
    form.setFieldsValue({ studyMethod: 200 });
  }, []);
  useEffect(() => {
    console.log(type, '打印看看type是什么');
    if (type === pageOpeTypeEnum['add']) {
      if (organizationType === 1) {
        //协会
        form.setFieldsValue({ objectType: 1, signRule: 1, modelType: 1 });
      }
      // 默认取上个位置
      // getCurrLocation({ entId }).then((res) => {
      //   const data = res.data as positionInfoValue;
      //   console.log(data, '打印看看地址信息');
      //   form.setFieldValue('positionInfoDto', data);
      //   const number = ++rowkey;
      //   setrowkey(number);
      // });
      // 目前添加进来，默认为空
      form.setFieldValue('positionInfoDto', { addressName: '', latitude: '', longitude: '', name: '', scope: '' });

      learnMethod = '200';
      form.setFieldValue('studyMethod', '200');
    } else if (type === pageOpeTypeEnum['edit'] && planCourseId) {
      setLoading(true);
      getOfflinePlanDetail(planCourseId)
        .then((res: any) => {
          const { data } = res;
          console.log('线下计划详情:', data);
          const initialFormValue: any = {};
          const {
            trainAddress,
            title,
            entList,
            linkInfo,
            signRule,
            signAddress,
            latitude,
            longitude,
            scope,
            intervalTime,
            isFace,
            trainTimeVoList,
            noTrainTimeVoList,
            specialTrainTimeVoList,
          } = data;
          if (organizationType === 1) {
            initialFormValue.positionInfoDto = {
              addressName: signAddress,
              latitude,
              longitude,
              scope,
            };

            initialFormValue.trainTimeDtoList = trainTimeVoList.map((el: any) => {
              return {
                value: el.week,
                startTrainTime: el.startTrainTime.slice(0, 5),
                endTrainTime: el.endTrainTime.slice(0, 5),
              };
            });
            initialFormValue.noTrainTimeDtoList = [...noTrainTimeVoList];
            initialFormValue.specialTrainTimeDtoList = specialTrainTimeVoList.map((el: any) => {
              return {
                trainTime: el.startSpecialTrainTime.slice(0, 10),
                startTime: el.startSpecialTrainTime.slice(11, 16),
                endTime: el.endSpecialTrainTime.slice(11, 16),
              };
            });
          }
          setIntervalType(data.intervalType.toString());
          form.setFieldsValue({
            ...initialFormValue,
            trainAddress,
            title,
            entList,
            linkInfo,
            signRule,
            intervalTime,
            // intervalType,
            isFace,
            // trainTimeVoList,
            // noTrainTimeVoList,
            specialTrainTimeVoList,
          });
          learnMethod = '200';
          form.setFieldValue('studyMethod', '200');
        })
        .finally(() => {
          setLoading(false);
        })
        .catch((err) => {
          console.log('--OfflineStudyPlan--getOfflinePlanDetail--err--:', err);
        });
    }
    // if (!isEmpty(previewDetail)) {
    //   //计划模板进来
    //   // console.log('--AddFixedStudyPlan--previewDetail--:', previewDetail);
    //   const { name, faceImg, guid, isCharge } = previewDetail;
    //   const initialFormVal: any = {
    //     title: name,
    //     cover: faceImg ? [{ uid: uuid(), url: faceImg }] : undefined,
    //   };
    //   form.setFieldsValue(initialFormVal);
    //   dealWidthStudyTemplate(guid, isCharge).then((studyPackageList) => {
    //     form.setFieldValue('studyPackageList', studyPackageList);
    //   });
    // }
    // }
  }, []);
  function getFieldValue(arg0: string) {
    throw new Error('Function not implemented.');
  }

  return (
    <>
      <ViewLoading show={loading} />
      <Form layout="horizontal" labelAlign="right" className={OStyle.formCont} form={form} {...formItemLayout}>
        <YmCollaPanes
          collPanesActiveKeys={collPanesActiveKeys}
          // onSetCollPanesActiveKeys={setCollPanesActiveKeys}
          paneKey={5}
          collapsible={false}
          headerTitle="基本信息"
        >
          {/* {studyPlanType} */}
          {/* {organizationType === 1 && (
            <> */}
          <Form.Item label="学习模式" name="studyMethod" rules={requireRules('请选择学习模式')}>
            <Radio.Group
              defaultValue={learnMethod}
              onChange={(e) => {
                onStudyPlanMethodChange(e.target.value);
                console.log(e.target.value, learnMethod, '打印看看现在是什么c');
              }}
              disabled={type !== pageOpeTypeEnum['add']}
            >
              <Radio value="100">线上学习</Radio>
              <Radio value="200">线下培训</Radio>
            </Radio.Group>
          </Form.Item>
          {/* </>
          )} */}
          {/* 预发时候，说去掉这个类型 */}
          {/* <Form.Item label="类型" required>
            <Space size={16}>
              <Select
                defaultValue="固定时间"
                style={{ width: '120px' }}
                options={[{ value: '固定时间', label: '固定时间' }]}
              />
            </Space>
          </Form.Item> */}
          <Form.Item label="培训位置" name="trainAddress">
            <Input showCount maxLength={199} placeholder="请输入"></Input>
          </Form.Item>
          <Form.Item label="培训名称" name="title" rules={requireRules('请输入计划名称')}>
            <Input showCount maxLength={88} placeholder="请输入"></Input>
          </Form.Item>
          <Form.Item label="学习对象" required wrapperCol={{ span: 19 }}>
            <Space>
              <Form.Item name="objectType" noStyle>
                <Select
                  defaultValue={1}
                  options={[
                    { label: '企业范围', value: 1 },
                    // { label: '服务号范围', value: 4 },
                  ]}
                />
              </Form.Item>
              <Form.Item noStyle>
                <Space>
                  <Form.Item
                    name="entList"
                    noStyle
                    {...EntSelectTree.fieldProps}
                    rules={requireRules('请选择学习对象企业')}
                  >
                    <TreeSelect {...EntSelectTree.treeSelectProps}></TreeSelect>
                  </Form.Item>
                  {/* <Form.Item name="studyObject" noStyle rules={requireRules('请选择学习对象人员')}>
                    <StudyObjectSelect optionsType={2} />
                  </Form.Item> */}
                </Space>
              </Form.Item>
              <Form.Item noStyle>
                <Select
                  value={4}
                  options={[
                    // { label: '全部人员', value: 1, disabled: true },
                    { label: '司机', value: 4, disabled: true },
                  ]}
                />
              </Form.Item>
            </Space>
          </Form.Item>
        </YmCollaPanes>
        <YmCollaPanes
          collPanesActiveKeys={collPanesActiveKeys}
          // onSetCollPanesActiveKeys={setCollPanesActiveKeys}
          paneKey={6}
          collapsible={false}
          headerTitle="规则设置"
        >
          <Form.Item label="关联信息" name="linkInfo" rules={requireRules('请选择关联信息')}>
            <Radio.Group>
              <Radio value={1}>暂无</Radio>
              {/* 安全码这期不做，预留着 */}
              {/* <Radio value={2}>安全码</Radio> */}
              <Radio value={3}>学习卡</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="是否需要签到/退" name="signRule" rules={requireRules('请选择是否需要签到/退')}>
            <Radio.Group>
              <Radio value={1}>不需要签到/签退</Radio>
              <Radio value={2}>只需要签到1次</Radio>
              <Radio value={3}>需要签到和签退</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.signRule !== currentValues.signRule}
          >
            {({ getFieldValue }) =>
              getFieldValue('positionInfoDto') &&
              (getFieldValue('signRule') === 2 || getFieldValue('signRule') === 3) ? (
                <Form.Item
                  // key={rowkey}
                  label="签到/签退位置"
                  name="positionInfoDto"
                  rules={requireRules('请选择学习位置')}
                  wrapperCol={{ span: 19 }}
                >
                  <TablePosition />
                  {/* <PositionInfo /> */}
                </Form.Item>
              ) : null
            }
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.signRule !== currentValues.signRule}
          >
            {({ getFieldValue }) =>
              getFieldValue('signRule') === 3 ? (
                <Form.Item
                  label="签退距签到最少时间"
                  name="intervalTime"
                  rules={requireRules('请输入签到距签退最少时间')}
                >
                  <InputNumber
                    style={{ width: 200 }}
                    minLength={1}
                    min={0}
                    placeholder="请输入"
                    maxLength={99}
                    addonAfter={selectAfter}
                  />
                  {/* <Select
              style={{ width: 80 }}
              options={[
                { label: '分钟', value: 0 },
                { label: '小时', value: 1 },
              ]}
            /> */}
                </Form.Item>
              ) : null
            }
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.signRule !== currentValues.signRule}
          >
            {({ getFieldValue }) =>
              getFieldValue('signRule') === 2 || getFieldValue('signRule') === 3 ? (
                <Form.Item label="是否需要人脸识别" name="isFace" rules={requireRules('请选择是否需要人脸识别')}>
                  <Radio.Group>
                    <Radio value={1}>是</Radio>
                    <Radio value={0}>否</Radio>
                  </Radio.Group>
                </Form.Item>
              ) : null
            }
          </Form.Item>
        </YmCollaPanes>
        <div className={OStyle.timeCont}>
          <YmCollaPanes
            collPanesActiveKeys={collPanesActiveKeys}
            // onSetCollPanesActiveKeys={setCollPanesActiveKeys}
            paneKey={7}
            collapsible={false}
            headerTitle="培训时间"
          >
            <Form.Item
              label="培训日期与时间"
              name="trainTimeDtoList"
              wrapperCol={{ span: 19 }}
              rules={requireRules('请添加培训日期与时间')}
            >
              <SelectWeekDays />
            </Form.Item>
            <Form.Item label="特殊无需培训日" name="noTrainTimeDtoList" wrapperCol={{ span: 19 }}>
              <SelNoStudyDays />
            </Form.Item>
            <Form.Item label="特殊培训日" name="specialTrainTimeDtoList" wrapperCol={{ span: 19 }}>
              <SelDayTimes />
            </Form.Item>
            {/* <Form.Item label="节假日" name="studyMethod10">
            <Checkbox checked={true} onChange={(v) => console.log(v)}>
              中国法定节假日不需培训学习
            </Checkbox>
          </Form.Item> */}
          </YmCollaPanes>
        </div>
      </Form>
    </>
  );
});
export default OfflineStudyPlan;
